
const baseUrl = 'http://api.9lele.com/public/index.php/api'
const loginUrl = 'http://127.0.0.1:8080'

// 引入加密
import {
	MD5
} from 'crypto-js'
import * as S from "@/utils/storage.js"

let requestArr = []
export const request = (option) => {
	const userInfo = S.getItem("userInfo")
	let keys = ''
	if (option.data) {
		let dataArr = Object.keys(option.data)
		if (dataArr.length > 0) {
			dataArr.sort()
			let sumStr = ''
			for (let i = 0; i < dataArr.length; i++) {
				sumStr += `${dataArr[i]}=${option.data[dataArr[i]]}&`
			}
			// console.log(sumStr.trim().slice(0, -1))
			// 
			keys = MD5(option.url + '?' + sumStr.trim().slice(0, -1)).toString()
			console.log(keys)
		}
	} else {
		keys = MD5(option.url).toString()
	}

	uni.showLoading({
		title: '加载中...'
	})
	return new Promise((resolve, reject) => {
		if (requestArr.includes(keys)) {
			// return
			console.log('请求失败', keys, 'keys', option.url)
			reject()
			// requestArr.splice(requestArr.indexOf(keys), 1)
		} else {
			requestArr.push(keys)
			uni.request({
				url: baseUrl + option.url, //仅为示例，并非真实的接口地址
				data: {
					...option.data
				},
				method: option.methods ? option.methods : 'GET',
				header: {
					// 'content-type': 'application/x-www-form-urlencoded', // 默认值
					'Token':userInfo?userInfo.token:"",
					'Sign':keys,
					...option.header
				},
				success: (res) => {
					if(res.data.code===0 && res.data.msg==="请先登录"){
						S.remove("userInfo")
						uni.showToast({
							title:"请先登录！",
							duration:2000,
							success: () => {
								uni.redirectTo({
									url:"/pages/login/login"
								})
							}
						})
						
					}else{
						resolve(res.data)
					}
					
				},
				fail: (err) => {
					reject(err)
				},
				complete: (res) => {
					// console.log(requestArr.includes(keys), option.url, keys, requestArr)
					requestArr.splice(requestArr.indexOf(keys), 1)
					uni.hideLoading()
				}
			})
		}

	})
}
export const loginrequest = (option) => {
	uni.showLoading({
		title: '加载中...'
	})
	return new Promise((resolve, reject) => {
		uni.request({
			url: loginUrl + option.url, //仅为示例，并非真实的接口地址
			data: {
				...option.data
			},
			method: option.methods ? option.methods : 'GET',
			header: {
				'content-type': 'application/x-www-form-urlencoded' // 默认值
			},
			success: (res) => {
				resolve(res.data)
			},
			fail: (err) => {
				reject(err)
			},
			complete: (res) => {
				uni.hideLoading()
			}
		})


	})
}